package com.et.util

import okhttp3.*
import java.io.*
import java.util.concurrent.TimeUnit


var client: OkHttpClient = OkHttpClient.Builder()
    .connectTimeout(20, TimeUnit.SECONDS)
    .writeTimeout(20, TimeUnit.SECONDS)
    .readTimeout(20, TimeUnit.SECONDS)
    .build()

data class Response(val success: Boolean, val code: Int, val body: String?) {
    override fun toString(): String {
        return "Response(success=$success, code=$code, body=$body)"
    }
}

fun okhttpRequest(request: Request): Call {
    return client.newCall(request)
}

fun httpPost(url: String, param: HashMap<String, Any>): Response {
    val builder = FormBody.Builder()
    param.forEach {
        builder.add(it.key, it.value.toString())
    }
    val formBody: FormBody = builder.build()
    val request: Request = Request.Builder()
        .post(formBody)
        .url(url)
        .build()
    val response: okhttp3.Response
    return try {
        response = client.newCall(request).execute()
        Response(response.isSuccessful, response.code, response.body?.string())
    } catch (e: IOException) {
        Response(false, 404, "IoException")
    }
}

fun File.download(url: String, callback: (p: Float) -> Unit) {
    val request: Request = Request.Builder().url(url).build()
    val response: okhttp3.Response
    try {
        response = client.newCall(request).execute()
    } catch (e: IOException) {
        callback(-1f)
        return
    }
    val responseBody: ResponseBody? = response.body
    responseBody?.let { body ->
        val l = body.contentLength()
        if (this.exists()) {
            if (l == this.length()) {
                callback(1f)
                return
            } else {
                deleteFile()
            }
        }
        if (this.exists()) return
        val fileOutputStream = FileOutputStream(this)
        BufferedOutputStream(fileOutputStream).use { output ->
            BufferedInputStream(body.byteStream()).use { input ->
                val dataBuf = ByteArray(1024)
                var readLen: Int = input.read(dataBuf)
                var p: Float
                var a = 0L
                while (readLen > -1) {
                    output.write(dataBuf, 0, readLen)
                    a += readLen
                    p = a.toFloat() / l
                    readLen = input.read(dataBuf)
                    callback(p)
                }
            }
        }
    }
}
